package com.example.lanouhn.firstapp.activity.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lanouhn.firstapp.R;
import com.example.lanouhn.firstapp.activity.adapter.FlagshipStoreAdapter;
import com.example.lanouhn.firstapp.activity.constants.Constants;
import com.example.lanouhn.firstapp.activity.model.FlagshipStore;
import com.example.lanouhn.firstapp.activity.utils.FlagshipStoreJson;
import com.example.lanouhn.firstapp.activity.utils.HttpUtils;
import com.example.lanouhn.firstapp.activity.view.xlistview.XListView;

import java.util.ArrayList;
import java.util.List;


//商城旗舰店界面（从全部商品跳转到）
public class FlagshipStoreActivity extends AppCompatActivity {

    //搜索
    private TextView tv_store_search;
    private EditText et_store_search;

    //搜索的数据集合

    private List<FlagshipStore> SList;

    //获取请求网址
    private String getRequestUrl() {
        return Constants.FLAGSHIP_STORE_URL
                + "&key=" + key + "&order=" + order + "&curpage=" + currentPage;
    }

    //定义变量
    private XListView listView;
    private RadioGroup radioGroup;
    //一个中间量集合
    private List<FlagshipStore> tempList;
    //定义商品id
    private String goods_id;
    //排序类型
    private int key = 1;//1代表新品，2代表价格 3代表销量 4代表人气
    //当前页
    private int currentPage = 1;
    //升降序标识
    private boolean orderFlag = true;
    private int order = 1;//升序1，降序2

    private boolean isFirstRequest = true;


    //数据集合
    private List<FlagshipStore> list;
    private FlagshipStoreAdapter adapter;
    //加载进度
    private ProgressBar progressBar;

    //返回
    private ImageView iv_back;
    //无搜索商品
    private TextView tv_noProduct;
    //弹出标题栏
    private LinearLayout ll_title;
    private ImageView iv_flagship_store;
    private boolean isImageView = true;

    private RelativeLayout rl_homePage;
    private RelativeLayout rl_classify;
    private RelativeLayout rl_shoppingCart;
    private RelativeLayout rl_myStore;
    //主线程
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            progressBar.setVisibility(View.GONE);

            switch (msg.what) {
                case 0:
                    Toast.makeText(FlagshipStoreActivity.this,
                            "网络链接失败，请稍后再试", Toast.LENGTH_SHORT).show();
                    break;
                case 1:

                    adapter = new FlagshipStoreAdapter(FlagshipStoreActivity.this, list);
                    listView.setAdapter(adapter);
                    listView.stopRefresh();
                    listView.setPullLoadEnable(true);
                    adapter.notifyDataSetChanged();
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Intent intent = new Intent(FlagshipStoreActivity.this, GoodsDetailsActivity.class);
                            intent.putExtra("goods_id", list.get(i - 1).getGoods_id());
                            startActivity(intent);
                        }
                    });
                    break;

                case 2:

                    list.addAll(tempList);
                    //刷新页面
                    adapter.notifyDataSetChanged();
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Intent intent = new Intent(FlagshipStoreActivity.this, GoodsDetailsActivity.class);
                            intent.putExtra("goods_id", list.get(i - 1).getGoods_id());
                            startActivity(intent);
                        }
                    });
                    //清空中间量集合
                    tempList.removeAll(tempList);
                    //停止加载
                    listView.stopLoadMore();
                    break;

                case 3:
                    adapter = new FlagshipStoreAdapter(FlagshipStoreActivity.this, SList);
                    listView.setAdapter(adapter);

                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Intent intent = new Intent(FlagshipStoreActivity.this, GoodsDetailsActivity.class);
                            intent.putExtra("goods_id", SList.get(i - 1).getGoods_id());
                            startActivity(intent);
                        }
                    });
                    tv_noProduct.setVisibility(View.GONE);
                    break;
                case 4:
                    tv_noProduct.setVisibility(View.VISIBLE);
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_flagship_store);

        //获取上个页面传过来的参数
        goods_id = getIntent().getStringExtra("goods_id");


        //加载进度
        progressBar = (ProgressBar) findViewById(R.id.progressBar);

       //找到控件
        initView();
        //点击旗舰店搜索按钮
        getStoreDataFromWeb();
        //获取网络请求数据
        getDataFromWeb();
        //监听事件
        initEvent();
    }

    private void initView() {
        tv_store_search = (TextView) findViewById(R.id.tv_store_search);
        et_store_search = (EditText) findViewById(R.id.et_store_search);

        tv_noProduct = (TextView) findViewById(R.id.tv_noProduct);

        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_flagship_store = (ImageView) findViewById(R.id.iv_flagship_store);

        listView = (XListView) findViewById(R.id.listView);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        //开启加载更多功能 设置上拉加载的开关
        listView.setPullLoadEnable(true);

        rl_homePage = (RelativeLayout) findViewById(R.id.rl_homePage);
        rl_classify = (RelativeLayout) findViewById(R.id.rl_classify);
        rl_shoppingCart = (RelativeLayout) findViewById(R.id.rl_shoppingCart);
        rl_myStore = (RelativeLayout) findViewById(R.id.rl_myStore);

    }


    private void initEvent() {


        //设置默认的RadioButton
        radioGroup.check(R.id.rb_newProduct);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {

                switch (i) {
                    case R.id.rb_newProduct://新品key=1
                        key = 1;
                        break;
                    case R.id.rb_price://价格key=2
                        key = 2;
                        if (orderFlag)
                            order = 1;
                        else
                            order = 2;

                        orderFlag = !orderFlag;
                        break;
                    case R.id.rb_sales://销量key=3
                        key = 3;
                        break;
                    case R.id.rb_popularity://人气key=4
                        key = 4;
                        break;
                }
                //重新获取数据并填充listView
                getDataFromWeb();

            }
        });
        //listView的刷新加载监听事件
        listView.setXListViewListener(new XListView.IXListViewListener() {

            @Override
            public void onRefresh() {

                //下拉刷新
                currentPage++;
                getDataFromWeb();
            }

            @Override
            public void onLoadMore() {
                //上拉更多
                currentPage++;
                getMoreDataFromWeb();

            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(FlagshipStoreActivity.this, GoodsDetailsActivity.class);
                intent.putExtra("goods_id", list.get(i - 1).getGoods_id());
                startActivity(intent);
            }
        });

        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //弹出标题栏监听事件
        iv_flagship_store.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isImageView) {
                    ll_title.setVisibility(View.VISIBLE);
                    isImageView = false;
                } else {
                    ll_title.setVisibility(View.GONE);
                    isImageView = true;
                }
            }
        });

        rl_homePage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(FlagshipStoreActivity.this,MainActivity.class);
                intent.putExtra("symbol",1);
                startActivity(intent);
            }
        });
        rl_classify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(FlagshipStoreActivity.this,MainActivity.class);
                intent.putExtra("symbol",2);
                startActivity(intent);
            }
        });
        rl_shoppingCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(FlagshipStoreActivity.this,MainActivity.class);
                intent.putExtra("symbol",3);
                startActivity(intent);
            }
        });
        rl_myStore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(FlagshipStoreActivity.this,MainActivity.class);
                intent.putExtra("symbol",4);
                startActivity(intent);
            }
        });
    }


    /**
     * 获取更多列表数据
     */
    private void getMoreDataFromWeb() {


        tempList = new ArrayList<>();
        //开启线程
        new Thread(new Runnable() {
            @Override
            public void run() {

                String result = HttpUtils.doGet(getRequestUrl());

                if (!result.equals("") && !result.equals("null")) {

                    //解析数据进行封装
                    tempList = FlagshipStoreJson.getFlagshipStore(result);
                    if (tempList.size() > 0)
                        //获取数据成功
                        handler.sendEmptyMessage(2);
                    else
                        handler.sendEmptyMessage(0);

                } else {
                    //获取数据失败
                    handler.sendEmptyMessage(0);
                }
            }
        }).start();


    }

    /**
     * 获取解析数据
     */

    private void getDataFromWeb() {


        //显示加载进度条
        if (isFirstRequest) {
            //加载进度
            progressBar.setVisibility(View.VISIBLE);
        }
        //开启线程
        new Thread(new Runnable() {
            @Override
            public void run() {

                //调用HttpUtils类，来请求网络获取Json数据
                String result = HttpUtils.doGet(getRequestUrl());

                //判断数据是否解析成功
                if (!result.equals("") && !result.equals("null")) {
                    //数据进行封装
                    list = FlagshipStoreJson.getFlagshipStore(result);

                    //判断解析出的集合的长度，有数据就显示，无数据就不显示
                    if (list.size() > 0) {
                        //获取数据成功
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }

                } else {
                    //失败
                    handler.sendEmptyMessage(0);
                }


            }
        }).start();

        isFirstRequest = false;
    }

    private void getStoreDataFromWeb() {


        //搜索按钮监听事件
        tv_store_search.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {


                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String inkeyword = et_store_search.getText().toString().trim();
                        //定义路径
                        String url = Constants.FLAGSHIP_STORE_URL +
                                "&key=" + key + "&order=" + order + "&curpage=" + currentPage + "&inkeyword=" + inkeyword;

                        String result = HttpUtils.doGet(url);
                        //判断数据是否解析成功
                        if (!result.equals("") && !result.equals("null")) {
                            //数据进行封装
                            SList = FlagshipStoreJson.getFlagshipStore(result);

                            //判断解析出的集合的长度，有数据就显示，无数据就不显示
                            if (SList.size() > 0) {
                                //获取数据成功
                                handler.sendEmptyMessage(3);
                            } else {
                                handler.sendEmptyMessage(4);
                            }

                        } else {
                            //失败
                            handler.sendEmptyMessage(4);
                        }

                    }
                }).start();
            }
        });
    }
}
